package com.wlts.wzy.DYGoodsModule.DYapi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wlts.wzy.util.http.JavaSign;
import lombok.SneakyThrows;
import org.apache.http.*;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class DyApiClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtils.class);

    @SneakyThrows
    public static JSONObject DYAoiGet(String Api, String method, String AppKey, String appSecret, String accesstoken, TreeMap<String, ?> paramJson) {
        //API协议版本，当前版本为2
        String v = "2";
        //业务参数   page：第几页（第一页为0，最大为99）    size：每页返回条数，最多支持100条

        //时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
        String str = appSecret + "app_key" + AppKey + "method" + method + "param_json" + JSON.toJSONString(paramJson) + "timestamp" + date + "v" + v + appSecret;


        //创建URLBuilder
        URIBuilder uriBuilder = new URIBuilder(Api);

        //1.创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //要求：设置请求的地址是：http://yun.itheima.com/search?keys=java
        String content = null;
        //2.创建HttpGet对象，设置URL地址
        HttpPost httpPost = new HttpPost(uriBuilder.build());

        TreeMap<String,String> param=new TreeMap<>();


        param.put("app_key", AppKey);
        param.put("method", method);
        param.put("access_token", accesstoken);
        param.put("param_json", JSON.toJSONString(paramJson));
        param.put("timestamp", date);
        param.put("v", "2");
        param.put("sign", JavaSign.stringToMD5(str));

        List<NameValuePair> params = new ArrayList<>(param.size());
        if (!param.isEmpty()) {
            for (Map.Entry<String, String> parameter : param.entrySet()) {
                params.add(new BasicNameValuePair(parameter.getKey(), parameter
                        .getValue()));
            }

        }
        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

        //使用httpClient发起响应获取repsonse
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            //4.解析响应，获取数据
            //判断状态码是否是200
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = response.getEntity();
                content = EntityUtils.toString(httpEntity, "utf8");
//                System.out.println(content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if(content==null){
            throw new Exception("链接失败！");
        }
        JSONObject jsonObject1 = JSONObject.parseObject(content);
        if(jsonObject1.getInteger("err_no")!=0){
            throw new Exception(jsonObject1.getString("message"));
        }
        return jsonObject1;

    }


    public static void main(String[] args) {

//        System.err.println(sendGet1("", ""));

    }


}
